const util = require('../../utils/util.js');
const checkLogin = require('../../utils/checkLogin.js');
const wxHttpHandler = require('../../utils/wxHttpHandler.js');
const api = require('../../APIConfig/apiConfig.js');
const QQMapWX = require('../../utils/qqmap-wx-jssdk.js')

var app = getApp();
var qqMapSDK;

Page({
  data: {
    showAuthorize: false,
    showDetails: false,
    allField: 0, //全部
    runField: 0, //运行
    stopField: 0, //停车
    alarmField: 0, //报警
    offLineField: 0, //离线
    markers: [],
    gpsSpeedF: '0', //时速
    gpsMileageF: '0', //里程
    stopTime: '0', //停车时长
    loation: '', //位置
    temp: '0', //温度
    status: '离线', //状态
  },

  onLoad: function (options) {
    qqMapSDK = new QQMapWX({
      key: 'EWDBZ-3BZ36-BDGSG-MMQHU-KW7OK-FDBMA'
    })
    // debugger
    // if (!wx.getStorageSync('authorize')) {
    //   app.globalData.hasUserInfo = false
    //   // this.setData({
    //   //   hasUserInfo: false
    //   // });
    // } else {
    //   app.globalData.hasUserInfo = true
    //   // this.setData({
    //   //   hasUserInfo: true
    //   // });
    // }
    // if (app.globalData.userInfo) {
    //   app.globalData.hasUserInfo = true
    //   this.setData({
    //     userInfo: app.globalData.userInfo,
    //     // hasUserInfo: true
    //   })
    // } else if (app.globalData.canIUse) {
    //   // debugger
    //   // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //   // 所以此处加入 callback 以防止这种情况
    //   app.userInfoReadyCallback = res => {
    //     app.globalData.hasUserInfo = true
    //     this.setData({
    //       userInfo: res.userInfo,
    //       // hasUserInfo: true
    //     })
    //   }
    // } else {
    //   // 在没有 open-type=getUserInfo 版本的兼容处理
    //   wx.getUserInfo({
    //     success: res => {
    //       app.globalData.userInfo = res.userInfo
    //       app.globalData.hasUserInfo = true
    //       this.setData({
    //         userInfo: res.userInfo,
    //         // hasUserInfo: true
    //       })
    //     }
    //   })
    // }

    // if (!app.globalData.hasUserInfo && app.globalData.canIUse) {
    //   this.isShowAuthorize();
    // }

    if (!wx.getStorageSync('userId')) {
      checkLogin()
    } else {
      console.log('queryRoute:' + wx.getStorageSync('userId'))
      this.queryRoute()
    }
  },

  onShow: function () {

    if (wx.getStorageSync('id') == '') {
      wx.showToast({
        title: '请先登录',
      })
      wx.navigateTo({
        url: '../Login/Login',
      })
    } else {
      this.getMainAnalysis()
      this.getMainVehicles()
    }

  },

  // 微信授权弹窗按钮
  getUserInfo: function (e) {
    //debugger
    if (e.detail.errMsg == "getUserInfo:ok") {
      app.globalData.userInfo = e.detail.userInfo
      wx.setStorageSync('authorize', true);
      wx.setStorageSync('userInfo', e.detail.userInfo);
      app.globalData.hasUserInfo = true
      app.globalData.showAuthorize = false
      this.setData({
        userInfo: e.detail.userInfo,
        // hasUserInfo: true,
        // showAuthorize:false
        showAuthorize: false
      })
      // app.checkLoginStatus();
      // app.selfDefinedLogin();
      checkLogin();
    }

  },

  //是否显示授权弹窗
  isShowAuthorize() {
    if ((!app.globalData.hasUserInfo && app.globalData.canIUse)) {
      this.setData({
        showAuthorize: true
      })
      return;
    }
    // //地理位置未授权 重新调起授权
    // wx.getSetting({
    //   success: (res) => {
    //     if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { //非初始化进入该页面,且未授权

    //     }
    //   }
    // })

  },

  //点击地图车辆
  markerTap: function (e) {
    var marker = this.data.markers[e.detail.markerId];
    var that = this

    this.getVehicleDetails(marker.vehicleId)
    qqMapSDK.reverseGeocoder({
      location: {
        latitude: marker.latitude,
        longitude: marker.longitude
      },
      success: function (addressRes) {
        console.log(addressRes.result.address)
        that.setData({
          loation: addressRes.result.address,
          showDetails: true
        })
        //这里打印出来很多的东西 就有你想要的地址名称
      }
    })
  },

  bindregionchange: function () {
    this.setData({
      showDetails: false
    })
  },

  bindTap: function () {
    wx.scanCode({
      onlyFromCamera: true,
      complete: (res) => {
        wx.navigateTo({
          url: '../bindAndUnbind/bindAndUnbind?type=0&keyWords=res',
        })
      },
    })
  },

  unBindTap:function(){
    wx.navigateTo({
      url: '../bindAndUnbind/bindAndUnbind?type=1&keyWords=',
    })
  },

  toAddvehicle: function () {
    wx.navigateTo({
      url: '../addVehicle/addVehicle',
    })
  },

  //获取统计数据
  getMainAnalysis: function () {
    let data = {}
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.getMainAnalysis + wx.getStorageSync('id'),
      data: data,
      fn: function (res) {
        if (res.code == 0) {
          that.setData({
            allField: res.data.vehicleCount,
            runField: res.data.onlineCount,
            stopField: res.data.stopCount,
            alarmField: res.data.alarmCount,
            offLineField: res.data.offlineCount,
          })
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },

  //车辆分布
  getMainVehicles: function () {
    let data = {}
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.getMainVehicles + wx.getStorageSync('id'),
      data: data,
      fn: function (res) {
        if (res.code == 0) {
          if (res.data != null && res.data.length > 0) {
            let i
            let marksTem = []
            for (i = 0; i < res.data.length; i++) {
              marksTem.push({
                id: i,
                iconPath: "../../assets/images/home/car.png",
                latitude: res.data[i].latitudeD,
                longitude: res.data[i].longitudeD,
                registrationNo: res.data[i].registrationNo,
                vehicleId: res.data[i].vehicleId,
                vehicleStatus: res.data[i].vehicleStatus,
                width: 20,
                height: 10,
                anchorX: 0,
                anchorY: 0,
              })
            }
            that.setData({
              markers: marksTem
            })
          }
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },

  //车辆详情
  getVehicleDetails: function (e) {
    console.log(e)
    let data = {
      uid: wx.getStorageSync('id'),
      vehicleId: e
    }
    const that = this
    wx.showLoading()
    wxHttpHandler({
      type: 'get',
      path: api.getVehicleDetails,
      data: data,
      fn: function (res) {
        if (res.code == 0) {
          that.setData({
            gpsMileageF: res.data.gpsMileageF,
            gpsSpeedF: res.data.gpsSpeedF,
            status: res.data.status,
            stopTime: res.data.stopTime,
            temp: res.data.temp
          })
          wx.hideLoading()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.desc,
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
      }

    })
  },



})